package com.ihr360.payroll.service.salarytasklet.step.writer;


import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.job.core.item.ItemWriter;
import com.ihr360.payroll.calc.StaffSalaryCalcPeriod;
import com.ihr360.payroll.dao.StaffPayPeriodTermSalaryRepository;
import com.ihr360.payroll.model.dto.salary.task.period.StaffPayPeriodTermSalary;
import com.ihr360.payroll.service.salarytasklet.convertor.StaffPayPeriodSalaryConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author davidwei
 */
@Component
public class CalcedStaffSalaryInfoWriter implements ItemWriter<Map<String, StaffSalaryCalcPeriod>> {
    @Autowired
    StaffPayPeriodTermSalaryRepository staffPayPeriodTermSalaryRepository;

    @Autowired
    StaffPayPeriodSalaryConvertor convertor;

    @Override
    public void write(List<? extends Map<String, StaffSalaryCalcPeriod>> staffSalaries) throws Exception {
        Optional<? extends Map<String, StaffSalaryCalcPeriod>> optional = staffSalaries.stream().findFirst();
        if (optional.isPresent()) {
            Map<String, StaffSalaryCalcPeriod> salaryCalcPeriodMap = optional.get();
            if (CollectionUtils.isNotEmpty(salaryCalcPeriodMap)) {
               List<StaffPayPeriodTermSalary> salaryDtos=salaryCalcPeriodMap.values().stream().map(s ->
                        convertor.convertEntityToDto(s)
                ).collect(Collectors.toList());
                staffPayPeriodTermSalaryRepository.save(salaryDtos);
            }
        }
    }
}